package com.tom.demo.array;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

public class Test26_RemoveDuplicate {
    public static void main(String[] args) {
        int[] nums = new int[]{1, 1, 2};
//        int i = removeDuplicates(nums);
//        System.out.println(i);


        nums = new int[]{1, 1, 1, 2, 2, 3};
        System.out.println(removeDuplicates3(nums));
        System.out.println("-----");
        Arrays.stream(nums).forEach(System.out::println);
        System.out.println("-----");

    }

    public static int removeDuplicates(int[] nums) {
        Set<Integer> s = new HashSet<>();
        for (int i = 0; i < nums.length; i++) {
            if (!s.contains(nums[i])) {
                s.add(nums[i]);
            } else {
                nums[i] = 99999;
            }
        }

        Arrays.sort(nums);
        return Long.valueOf(Arrays.stream(nums).filter(n -> n != 99999).count()).intValue();
    }

    public static int removeDuplicates2(int[] nums) {
        int[] array = Arrays.stream(nums).distinct().toArray();
        System.arraycopy(array, 0, nums, 0, array.length);
        return array.length;
    }

    public static int removeDuplicates3(int[] nums) {
        if (nums.length <= 2) {
            return nums.length;
        }
        int slow = 2;
        int fast = 2;
        while (fast < nums.length) {
            if (nums[slow - 2] != nums[fast]) {
                nums[slow] = nums[fast];
                ++slow;
            }
            ++fast;
        }
        return slow;
    }
}
